<template>
  <div class="edit-menu">
    <a-modal
      :title="updateTitles"
      width="800px"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="requestSpinning" tip="正在加载数据中...">
        <a-form :form="form" :label-col="{ span: 9 }" :wrapper-col="{ span: 14 }">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-form-item label="父级菜单">
                <a-tree-select
                  v-decorator="['PID', { initialValue: '0', rules: [{ required: true, message: '请选择父级菜单!', whitespace: true, trigger: 'change' }] }]"
                  allowClear
                  show-search
                  treeNodeFilterProp="title"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="parentTreeList"
                  placeholder="请选择父级菜单"
                  searchPlaceholder="输入菜单名称进行筛选"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  菜单标题
                  <a-tooltip placement="top" title="路由标题, 用于显示面包屑, 页面标题 例如：菜单管理（路由meta中的title值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input
                  v-decorator="['Menu_Title', { initialValue: '', rules: [{ required: true, message: '请输入菜单标题!', whitespace: true, trigger: 'change' }] }]"
                  autocomplete="off"
                  placeholder="路由中的title值"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :validate-status="validateStatus"
                :help="helps"
                has-feedback
              >
                <template slot="label">
                  菜单名称
                  <a-tooltip placement="top" title="路由名称, 必须设置,且不能重名 例如: menu（路由中的name值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input
                  v-decorator="['Menu_KeyName', {
                    initialValue: '',
                    rules: [
                      { required: true, message: '请输入菜单名称', whitespace: true, trigger: 'change' }
                    ]
                  }]"
                  placeholder="路由中的name值"
                  autocomplete="off"
                  @change="changeMenuTitle"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="菜单图标">
                <a-input
                  v-decorator="['Menu_Icon', { initialValue: '' }]"
                  placeholder="请输入菜单图标">
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  组件路径
                  <a-tooltip placement="top" title="菜单对应的具体vue页面文件路径views的下级路径, 例如: /system/menu/index 目录类型: 填写RouteView（路由中的component值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input
                  v-decorator="['Menu_Address', {
                    initialValue: '',
                    rules: [
                      { required: false, message: '请输入组件路径!', whitespace: true, trigger: 'change' }
                    ]
                  }]"
                  autocomplete="off"
                  placeholder="路由中的component值" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  路由路径
                  <a-tooltip placement="top" title="访问此页面自定义的url地址，建议/开头书写，例如: /system/menu（路由中的path值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input
                  v-decorator="['Menu_Url', { initialValue: '', rules: [{ required: true, message: '请输入路由路径!', whitespace: true, trigger: 'change' }] }]"
                  autocomplete="off"
                  placeholder="路由中的path值" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  权限标识
                  <a-tooltip placement="top" title="用于控制按钮是否显示">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-select
                  v-decorator="['Menu_Role', { initialValue: [] }]"
                  mode="multiple"
                  :maxTagCount="2"
                  placeholder="请选择权限标识"
                >
                  <a-select-option v-for="(item, index) in jurisdictionList" :key="index" :value="item.DROPKEY">{{ item.DROPVALUE }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否外链">
                <a-radio-group
                  v-decorator="['Menu_IfLink', { initialValue: '0', rules: [{ required: false, message: '请选择是否外链!' }] }]"
                  @change="handleChangeLink"
                >
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  打开方式
                  <a-tooltip placement="top" title="菜单链接跳转目标, 参考 html a 标签（路由meta中的target值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-select
                  v-decorator="['Menu_Open', { rules: [{ required: false, message: '请输入外链/内嵌时链接地址!' }] }]"
                  :disabled="!isExternalLinks"
                  allowClear
                  placeholder="外链打开方式">
                  <a-select-option value="_blank">新窗口</a-select-option>
                  <!-- <a-select-option value="_self">默认</a-select-option> -->
                  <!-- <a-select-option value="_parent">父框架</a-select-option> -->
                  <!-- <a-select-option value="_top">整个窗口</a-select-option> -->
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  链接地址
                  <a-tooltip placement="top" title="用于外链/内嵌时链接地址(http:xxx.com)">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input
                  v-decorator="['Menu_LinkAddress', { initialValue: '', rules: [{ required: false, message: '请输入外链/内嵌时链接地址!' }] }]"
                  :disabled="!isExternalLinks"
                  placeholder="外链/内嵌时链接地址(http:xxx.com)" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  菜单排序
                  <a-tooltip placement="top" title="根据序号升序排列">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input-number
                  v-decorator="['Menu_Sort', { initialValue: '' }]"
                  placeholder="菜单排序值"
                  :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  重定向地址
                  <a-tooltip placement="top" title="重定向地址, 访问这个路由时,自定义进行重定向（路由中的redirect值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-input
                  v-decorator="['Menu_Redirect', { initialValue: '' }]"
                  autocomplete="off"
                  placeholder="重定向地址" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  显示在侧边栏
                  <a-tooltip placement="top" title="控制路由和子路由是否显示在侧边栏（路由meta中的show值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-select
                  v-decorator="['Menu_IfLeftView', { initialValue: '1', rules: [{ required: true, message: '请选择是否显示在侧边栏!' }] }]"
                  placeholder="是否显示在侧边栏"
                >
                  <a-select-option value="0">否</a-select-option>
                  <a-select-option value="1">是</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  路由缓存
                  <a-tooltip placement="top" title="缓存该路由（路由meta中的keepAlive值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-radio-group
                  v-decorator="['Menu_IfRouteCache', { initialValue: '0' }]"
                >
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  隐藏子菜单
                  <a-tooltip placement="top" title="用于隐藏菜单时，递归到父菜单显示 选中菜单项（路由meta中的hideChildren值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-radio-group
                  v-decorator="['Menu_IfHideChildren', { initialValue: '0' }]"
                >
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <template slot="label">
                  隐藏页面标题栏
                  <a-tooltip placement="top" title="隐藏 PageHeader 组件中页面带的 面包屑和页面标题栏（路由meta中的hiddenHeaderContent值）">
                    <span><a-icon type="question-circle" /></span>
                  </a-tooltip>
                </template>
                <a-radio-group
                  v-decorator="['Menu_IfPageHerder', { initialValue: '0' }]"
                >
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="启用菜单">
                <a-radio-group
                  v-decorator="['Menu_IfEnable', { initialValue: '1' }]"
                >
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { getTreeList, getDropdownList } from '@/api/common'
import { setMenus, getMenuInfo, verificationTitle } from '@/api/system'
import debounce from 'lodash.debounce'
import pick from 'lodash.pick'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      confirmLoading: false,
      requestSpinning: false,
      isExternalLinks: false,
      form: this.$form.createForm(this, { name: 'editMenu' }),
      validateStatus: '',
      helps: '',
      parentTreeList: [{
        title: '无',
        value: '0',
        key: '0',
        children: []
      }],
      jurisdictionList: []
    }
  },
  computed: {
    updateTitles: function () {
      const _type = this.propsData.type
      let _texts = null
      if (_type === 'add-menu') {
        _texts = '新增菜单'
      } else if (_type === 'add-sonMenu') {
        _texts = '新增子菜单'
      } else {
        _texts = '修改菜单'
      }
      return _texts
    }
  },
  watch: {
    propsData: function () {
      this.fetchMenu()
    }
  },
  methods: {
    fetchMenu () {
      const { propsData: { id, type }, form: { setFieldsValue }, $message } = this
      this.requestSpinning = true
      const tree = new Promise((resolve, reject) => {
        getTreeList({ mode: 'module' }).then(res => {
          resolve(res)
        })
      })
      const jurisdiction = new Promise((resolve, reject) => {
        getDropdownList({ PmKey: 'permissionidentification' }).then(res => {
          resolve(res)
        })
      })
      const info = new Promise((resolve, reject) => {
        if (type === 'edit-menu') {
          getMenuInfo({ moduleID: id }).then(res => {
            resolve(res)
          })
        } else {
          resolve()
        }
      })
      Promise.all([tree, jurisdiction, info]).then(res => {
        this.parentTreeList.map(item => {
          item.children = res[0]
          return item
        })
        this.jurisdictionList = res[1]
        if (type === 'add-sonMenu') {
          this.$nextTick(function () {
            setFieldsValue({ PID: id })
          })
        }
        if (type === 'edit-menu') {
          const result = res[2].data
          result.Menu_Role = result.Menu_Role === '' ? [] : result.Menu_Role.split(',')
          result.Menu_Open = result.Menu_Open === '' ? [] : result.Menu_Open.split(',')
          // eslint-disable-next-line no-unneeded-ternary
          this.isExternalLinks = result.Menu_IfLink === '1' ? true : false
          this.$nextTick(function () {
            setFieldsValue(pick(result, ['PID', 'Menu_Type', 'Menu_Title', 'Menu_KeyName', 'Menu_Icon', 'Menu_Address', 'Menu_Sort', 'Menu_Redirect', 'Menu_IfLeftView', 'Menu_IfRouteCache', 'Menu_IfHideChildren', 'Menu_IfPageHerder', 'Menu_IfEnable', 'Menu_IfLink', 'Menu_Open', 'Menu_LinkAddress', 'Menu_Url', 'Menu_Role']))
          })
        }
      }).catch((err) => {
        $message.error(err)
      }).finally(() => {
        this.requestSpinning = false
      })
    },
    changeMenuTitle: debounce(function () {
      const { form: { validateFields } } = this
      validateFields(['Menu_KeyName'], (errors, values) => {
        if (!errors) {
          this.validateStatus = 'validating'
          this.helps = '正在核验菜单名称是否重复...'
          verificationTitle({ ModuleKeyName: values.Menu_KeyName }).then(res => {
            if (res.code === 200) {
              this.validateStatus = 'success'
              this.helps = res.msg
            } else {
              this.validateStatus = 'error'
              this.helps = res.msg
            }
          }).catch(() => {
            this.validateStatus = ''
            this.helps = ''
          })
        } else {
          this.validateStatus = 'error'
          this.helps = '请输入菜单名称'
        }
      })
    }, 1000, { leading: false }),
    handleChangeLink (e) {
      // eslint-disable-next-line no-unneeded-ternary
      this.isExternalLinks = e.target.value === '1' ? true : false
    },
    handleJurisdiction (chooselist) {
      const result = []
      const { jurisdictionList } = this
      jurisdictionList.length > 0 && jurisdictionList.forEach(i => {
        chooselist.length > 0 && chooselist.forEach(j => {
          if (i.DropKey === j) {
            result.push({
              moduleKidKey: i.DropKey,
              moduleKidName: i.DropValue
            })
          }
        })
      })
      return result
    },
    handleSubmit () {
      const { form: { validateFields }, propsData: { type, id }, $message } = this
      validateFields({ force: true }, (err, values) => {
        if (!err) {
          const submitData = Object.assign({}, values, {
            ID: id || '',
            Menu_Url: values.Menu_IfLink === '1' ? values.Menu_LinkAddress : values.Menu_Url,
            Menu_Role: values.Menu_Role.join(),
            Menu_Open: (!values.Menu_Open || values.Menu_Open === '') ? '' : values.Menu_Open.join(),
            Menu_IfLeftView: values.Menu_IfLeftView,
            CreateUserID: this.$store.getters.userid,
            CreateUserName: this.$store.getters.name,
            CreateDateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            Mode: 0,
            menurolelist: this.handleJurisdiction(values.Menu_Role)
          })
          delete submitData.Menu_Type
          this.confirmLoading = true
          setMenus({
            State: type === 'edit-menu' ? 'update' : 'add',
            sys_module_Modules: submitData
          }).then(res => {
            if (res.code === 200) {
              $message.success('提交成功', 3)
              this.handleCancel()
              this.$parent.$parent.$refs.table.refresh(true)
            } else {
              $message.error('提交失败', 3)
            }
          }).catch((err) => {
            $message.error(err, 3)
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.validateStatus = ''
      this.helps = ''
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/.ant-input-number {
    width: 100%;
  }
</style>
